//
//  WDWDGroMoreRewardVideoManager.m
//  WDGroMore
//
//  Created by little People on 2023/7/26.
//

#import "WDWDGroMoreRewardVideoManager.h"
#import "WDGroMoreHeader.h"
#import "WDBMS.h"
#import "WDGroMoreThinkingManager.h"

@interface WDWDGroMoreRewardVideoManager ()<BUNativeExpressRewardedVideoAdDelegate,BUMNativeExpressRewardedVideoAdDelegate>
@property (nonatomic, assign) BOOL shouldShowAd;
@property (nonatomic, strong) BUNativeExpressRewardedVideoAd * rewardedVideoAd;
@property (nonatomic, copy) NSString * userUUId;
@end

@implementation WDWDGroMoreRewardVideoManager
static WDWDGroMoreRewardVideoManager *_manager = nil;

+ (instancetype)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (void)createRewardedAdWithPlacementId:(NSString *)placementId userId:(NSString *)userId {
    NSLog(@"[Reward] Create ad with placementId: %@ userId: %@", placementId, userId);
    self.userUUId = userId;
    BUAdSlot *adslot = [[BUAdSlot alloc]init];
    adslot.ID = placementId;
    adslot.mediation.mutedIfCan = NO;
    adslot.mediation.bidNotify = YES;
    adslot.mediation.scenarioID = @"123321";

    BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
    model.userId = @"123";
    model.rewardName = @"rewardName";
    model.rewardAmount = 100;
    model.extra = @"{}";

    self.rewardedVideoAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlot:adslot rewardedVideoModel:model];
    self.rewardedVideoAd.delegate = self;
    self.rewardedVideoAd.rewardPlayAgainInteractionDelegate = self;
    [self.rewardedVideoAd loadAdData];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_REQUEST
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_REQUEST}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_REQUEST
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)showRewardedAd {
    NSLog(@"[Reward] Try to show ad");
//    [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_button_click rewardVideoAd:self.rewardedVideoAd];
    if (self.rewardedVideoAd.mediation.isReady) {
        NSLog(@"[Reward] Ad is ready");
        if ([WDGroMoreDelegateManager manager].delegate &&
            [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardAdShow:)]) {
            [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardAdShow:self.rewardedVideoAd];
        }
//        [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_show_start rewardVideoAd:self.rewardedVideoAd];
        [self.rewardedVideoAd showAdFromRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    } else {
        NSLog(@"[Reward] Ad not ready, load again");
        self.shouldShowAd = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([WDGroMoreDelegateManager manager].delegate &&
                [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardAdReady:)]) {
                [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardAdReady:self.rewardedVideoAd.mediation.isReady];
            }
            [self rewardVideoAdLoad];
        });
    }
}

- (void)rewardVideoAdLoad {
    NSLog(@"[Reward] Load ad");
//    [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_load_start rewardVideoAd:self.rewardedVideoAd];
    [self createRewardedAdWithPlacementId:[WDGroMoreJosnManager GroMoreRewardAdIdForSDKConfigFile] userId:self.userUUId];
}

#pragma mark - BUNativeExpressRewardedVideoAdDelegate

- (void)nativeExpressRewardedVideoAdDidLoad:(BUNativeExpressRewardedVideoAd *)rewardVideoAd {
    NSLog(@"✅ [Reward] Ad did load");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:rewardVideoAd];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_FILL
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FILL,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FILL
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardVideoAdDidLoad:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardVideoAdDidLoad:rewardVideoAd];
    }
//    [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_load_sucess rewardVideoAd:rewardVideoAd];

    if (self.shouldShowAd) {
        self.shouldShowAd = NO;
        if ([WDGroMoreDelegateManager manager].delegate &&
            [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardAdShow:)]) {
            [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardAdShow:self.rewardedVideoAd];
        }
        [self.rewardedVideoAd showAdFromRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    }
}

- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error {
    NSLog(@"❌ [Reward] Load failed: %@", error.localizedDescription);
}

- (void)nativeExpressRewardedVideoAdServerRewardDidFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error {
    NSLog(@"[Reward] Server reward failed: %@", error.localizedDescription);
}

- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify {
    NSLog(@"✅ [Reward] Server reward success");
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardedVideoAdServerRewardDidSucceed:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardedVideoAdServerRewardDidSucceed:rewardedVideoAd];
    }
}

- (void)nativeExpressRewardedVideoAdDidVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd {
    NSLog(@"[Reward] Ad did visible");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:rewardedVideoAd];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_SHOW,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_SHOW
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    [[WDGroMoreThinkingManager manager]thinkingTrackEventWithKey:@"AD_RV_show" jsonStr:@{BMS_PARAM_WDS:BMS_WDS_AD_SHOW,
                                                                                         BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                                                                         BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                                                                         BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}];

//    [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_show_start rewardVideoAd:rewardedVideoAd];
}

- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardVideoAd {
    NSLog(@"[Reward] Ad did close");
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardVideoDelegateWithClose:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardVideoDelegateWithClose:rewardVideoAd];
    }
    [self rewardVideoAdLoad];
}

- (void)nativeExpressRewardedVideoAdDidPlayFinish:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error {
    NSLog(@"[Reward] Play finished, error: %@", error.localizedDescription);
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:rewardedVideoAd];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION_DONE
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FINISH,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FINISH
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardVideoAdDidPlayFinish:didFailWithError:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardVideoAdDidPlayFinish:rewardedVideoAd didFailWithError:error];
    }
    if (!error) {
//        [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_show_end rewardVideoAd:rewardedVideoAd];
    } else {
//        [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_show_fail rewardVideoAd:rewardedVideoAd];
    }
}

- (void)nativeExpressRewardedVideoAdViewRenderFail:(BUNativeExpressRewardedVideoAd *)rewardVideoAd error:(NSError *_Nullable)error {
    NSLog(@"[Reward] Render failed: %@", error.localizedDescription);
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardVideoAdDidShowFailed:error:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardVideoAdDidShowFailed:rewardVideoAd error:error];
    }
}

- (void)nativeExpressRewardedVideoAdDidClickSkip:(BUNativeExpressRewardedVideoAd *)rewardVideoAd {
    NSLog(@"[Reward] Click skip");
//    [[WDGroMoreBmsReportManager manager]rewardVideoBmsEventWithEventName:BMS_EVENT_ad_show_skip rewardVideoAd:rewardVideoAd];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreRewardVideoAdDidClickSkip:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreRewardVideoAdDidClickSkip:rewardVideoAd];
    }
}

- (void)nativeExpressRewardedVideoAdDidShowFailed:(BUNativeExpressRewardedVideoAd *_Nonnull)rewardedVideoAd error:(NSError *_Nonnull)error {
    NSLog(@"❌ [Reward] Show failed: %@", error.localizedDescription);
}

- (void)nativeExpressRewardedVideoAdDidClick:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd {
    NSLog(@"👉 [Reward] Ad clicked");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:rewardedVideoAd];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_CLICK
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_CLICK,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_CLICK
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

@end
